package club.yuit.rmq.service;

import club.yuit.rmq.ClientConfig;
import club.yuit.rmq.ClientServiceProviderFactory;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.SessionCredentials;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.MessageListener;
import org.apache.rocketmq.client.apis.consumer.PushConsumer;
import org.apache.rocketmq.client.apis.consumer.SimpleConsumer;

import java.util.Map;

/**
 * @author: yuit
 * @date: 2023/12/12 13:26
 */
public class ConsumerService {

    private ClientServiceProvider provider;

    public ConsumerService(){
        provider = ClientServiceProviderFactory.getProvider();
    }


    public SimpleConsumer simpleConsumer(String group, Map<String, FilterExpression> filterExpressions){

        try {

            String accessKey = System.getProperty("accessKey");
            String secretKey = System.getProperty("secretKey");
            String endpoints = System.getProperty("endpoints");
            return provider.newSimpleConsumerBuilder()
                    .setClientConfiguration(
                            ClientConfig.clientConfiguration(accessKey,secretKey,endpoints)
                    )
                    .setConsumerGroup(group)
                    .setSubscriptionExpressions(filterExpressions)
                    .build();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }

    public PushConsumer pushConsumer(String group, Map<String, FilterExpression> filterExpressions, MessageListener listener){

        try {

            String accessKey = System.getProperty("accessKey");
            String secretKey = System.getProperty("secretKey");
            String endpoints = System.getProperty("endpoints");

            SessionCredentials sessionCredentials = new SessionCredentials(accessKey,secretKey);

            return provider.newPushConsumerBuilder()
                    .setClientConfiguration(
                            ClientConfig.clientConfiguration(accessKey,secretKey,endpoints)
                    )
                   .setConsumerGroup(group)
                   .setSubscriptionExpressions(filterExpressions)
                    .setMessageListener(listener)
                   .build();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }


}
